1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/*!
`isotope` symbols
*/
use super::*;

mod set;
pub use set::*;

/// An `isotope` symbol
#[derive(Clone)]
pub struct Symbol {
    /// The ID of this symbol
    id: SymbolId,
    /// The (cached) free variable set of this symbol
    fv: SymbolSet,
}

impl Symbol {
    /// Get the ID for this symbol
    #[inline]
    pub fn id(&self) -> &SymbolId {
        &self.id
    }
}

impl From<SymbolId> for Symbol {
    fn from(id: SymbolId) -> Symbol {
        let mut fv = id.def_fv().clone();
        if id.is_fv() {
            // The identity is *covariant*, not invariant!
            fv.insert(id.clone(), Dependency::USED.of(&id));
        }
        Symbol { id, fv }
    }
}

impl From<Symbol> for SymbolId {
    fn from(sym: Symbol) -> SymbolId {
        sym.id
    }
}

impl PartialEq for Symbol {
    #[inline]
    fn eq(&self, other: &Symbol) -> bool {
        self.id == other.id
    }
}

impl Eq for Symbol {}

impl Debug for Symbol {
    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        Debug::fmt(&self.id, fmt)
    }
}

impl Hash for Symbol {
    #[inline]
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        self.id.hash(hasher)
    }
}

impl PartialOrd for Symbol {
    #[inline]
    fn partial_cmp(&self, other: &Symbol) -> Option<Ordering> {
        self.id.partial_cmp(&other.id)
    }
}

impl Ord for Symbol {
    #[inline]
    fn cmp(&self, other: &Symbol) -> Ordering {
        self.id.cmp(&other.id)
    }
}

impl Value for Symbol {
    #[inline]
    fn is_ty(&self) -> bool {
        self.ty().is_kind()
    }
    #[inline]
    fn is_groupoid(&self) -> bool {
        //TODO: think about groupoid kinds...
        false
    }
    #[inline]
    fn is_instant(&self) -> bool {
        self.ty().is_lifetime()
    }
    #[inline]
    fn into_enum(self) -> ValueEnum {
        ValueEnum::Symbol(self)
    }
    #[inline]
    fn into_valid(self) -> ValId {
        ValId::new_direct(ValueEnum::Symbol(self))
    }
    #[inline]
    fn ty(&self) -> &ValId {
        self.id.ty()
    }
    #[inline]
    fn fv(&self) -> &SymbolSet {
        &self.fv
    }
    #[inline]
    fn def_fv(&self) -> &SymbolSet {
        self.id.def_fv()
    }
    #[inline]
    fn code(&self) -> u64 {
        self.id().code()
    }
    #[inline]
    fn eval_in_ctx(&self, ctx: &mut EvalCtx) -> Option<ValId> {
        if let Some(mapping) = ctx.get(self.id()).cloned() {
            return Some(mapping);
        }
        if let Some(swapped_symbol) = self.id().new_in_ctx(ctx) {
            let val = Symbol::from(swapped_symbol).into_valid();
            ctx.def_flush_unchecked(self.id().clone(), val.clone());
            Some(val)
        } else {
            None
        }
    }
    #[inline]
    fn try_apply_in_ctx(&self, arg: &ValId, ctx: &mut EvalCtx) -> Result<Application, Error> {
        if let Some(mapping) = ctx.get(self.id()).cloned() {
            return mapping.try_apply_in_ctx(arg, ctx);
        }
        Ok(Application::Abstract(None))
    }
}

/// An `isotope` symbol ID
///
/// These are compared by address
#[derive(Clone)]
pub struct SymbolId(Arc<SymbolDesc>);

impl SymbolId {
    /// Get the descriptor of this symbol
    #[inline]
    pub fn desc(&self) -> &SymbolDesc {
        &self.0
    }
    /// Get whether this symbol is a free variable
    #[inline]
    pub fn is_fv(&self) -> bool {
        //TODO: this
        true
    }
    /// Get this symbol's definitional free variable set
    #[inline]
    pub fn def_fv(&self) -> &SymbolSet {
        &self.ty().fv()
    }
    /// Construct a new parameter symbol ID
    #[inline]
    pub fn param(ty: ValId) -> Result<SymbolId, Error> {
        SymbolDesc::new(ty).map(SymbolId::from)
    }
    /// Construct a new parameter symbol ID with a given maximal usage
    #[inline]
    pub fn param_with(ty: ValId, max_usage: Usage) -> Result<SymbolId, Error> {
        SymbolDesc::new_with(ty, max_usage).map(SymbolId::from)
    }
    /// Convert this symbol into a `ValId`
    #[inline]
    pub fn into_valid(self) -> ValId {
        Symbol::from(self).into_valid()
    }
    /// Get the type of this symbol
    #[inline]
    pub fn ty(&self) -> &ValId {
        self.0.ty()
    }
    /// Get this symbol ID as a pointer
    #[inline]
    pub fn as_ptr(&self) -> *const SymbolDesc {
        Arc::as_ptr(&self.0)
    }
    /// Get the code of this symbol ID
    #[inline]
    pub fn code(&self) -> u64 {
        Arc::as_ptr(&self.0) as usize as u64
    }
    /// Attempt to match a value to this symbol, yielding a constraint-vector on success
    #[inline]
    pub fn match_symbol(&self, value: &ValId) -> Result<Match, Error> {
        //TODO: fix variance...
        self.desc().ty().contains(value)
    }
    /// Evaluate and validate a symbol in a context
    /// Return `None` if this symbol is valid
    #[inline]
    pub fn eval_in_ctx(&self, ctx: &mut EvalCtx) -> Result<Option<SymbolId>, Error> {
        if let Some(symbol) = ctx.get(self) {
            match symbol.as_enum() {
                ValueEnum::Symbol(s) => Ok(Some(s.id().clone())),
                _ => Err(Error::NotASymbol),
            }
        } else {
            Ok(self.new_in_ctx(ctx))
        }
    }
    /// Get the maximal usage of this symbol
    #[inline]
    pub fn max_usage(&self) -> Usage {
        self.0.max_usage()
    }
    /// Generate a new symbol with the types evaluated in a context
    /// Return `None` if this symbol is valid
    #[inline]
    pub fn new_in_ctx(&self, ctx: &mut EvalCtx) -> Option<SymbolId> {
        self.ty.eval_in_ctx(ctx).map(|ty| {
            SymbolId::param_with(ty, self.max_usage())
                .expect("Normalized types must be valid types")
        })
    }
}

impl Deref for SymbolId {
    type Target = SymbolDesc;
    fn deref(&self) -> &SymbolDesc {
        &self.0
    }
}

impl From<SymbolDesc> for SymbolId {
    #[inline]
    fn from(mut desc: SymbolDesc) -> SymbolId {
        desc.ty.normalize();
        SymbolId(Arc::new(desc))
    }
}

impl PartialEq for SymbolId {
    #[inline]
    fn eq(&self, other: &SymbolId) -> bool {
        self.as_ptr() == other.as_ptr()
    }
}

impl PartialEq<ValId> for SymbolId {
    #[inline]
    fn eq(&self, other: &ValId) -> bool {
        match other.as_enum() {
            ValueEnum::Symbol(other) => self == other.id(),
            _ => false,
        }
    }
}

impl PartialEq<SymbolId> for ValId {
    #[inline]
    fn eq(&self, other: &SymbolId) -> bool {
        other.eq(self)
    }
}

impl Eq for SymbolId {}

impl Debug for SymbolId {
    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "Symbol({:x})", self.code())
    }
}

impl Hash for SymbolId {
    #[inline]
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        self.as_ptr().hash(hasher)
    }
}

impl PartialOrd for SymbolId {
    #[inline]
    fn partial_cmp(&self, other: &SymbolId) -> Option<Ordering> {
        self.as_ptr().partial_cmp(&other.as_ptr())
    }
}

impl Ord for SymbolId {
    #[inline]
    fn cmp(&self, other: &SymbolId) -> Ordering {
        self.as_ptr().cmp(&other.as_ptr())
    }
}

/// A descriptor for an `isotope` symbol
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SymbolDesc {
    /// This symbol's type
    ty: ValId,
    /// This symbol's maximal usage
    max_usage: Usage,
}

impl SymbolDesc {
    /// Create a new symbol descriptor with the given maximal usage
    pub fn new_with(ty: ValId, max_usage: Usage) -> Result<SymbolDesc, Error> {
        let max_linearity = ty.elem_linearity()?;
        Ok(SymbolDesc {
            ty,
            max_usage: max_usage & max_linearity.max_usage(),
        })
    }
    /// Create a new symbol descriptor with the maximum possible linearity
    pub fn new(ty: ValId) -> Result<SymbolDesc, Error> {
        let max_usage = ty.elem_linearity()?.max_usage();
        Ok(SymbolDesc { ty, max_usage })
    }
    /// Get the type of this symbol descriptor
    pub fn ty(&self) -> &ValId {
        &self.ty
    }
    /// Get this symbol descriptor's maximal usage
    pub fn max_usage(&self) -> Usage {
        self.max_usage
    }
    /// Get this symbol descriptor's type linearity
    pub fn ty_linearity(&self) -> Linearity {
        self.ty.elem_linearity().expect("Types have a linearity")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn symbol_id_identity() {
        let b = Bool.into_valid();
        let x = SymbolId::param(b.clone()).unwrap();
        let y = SymbolId::param(b.clone()).unwrap();
        assert_eq!(*x.ty(), b);
        assert_eq!(x.ty().as_ptr(), b.as_ptr());
        assert_ne!(x, y);
        assert_eq!(x.0, y.0);
        assert_eq!(
            *x.0,
            SymbolDesc {
                ty: b,
                max_usage: Usage::OBSERVED
            }
        );
    }

    #[test]
    fn symbol_free_variables() {
        let ty = SymbolId::param(SET.clone()).unwrap();
        let ty_s = Symbol::from(ty.clone()).into_valid();
        let mut ty_set = SymbolSet::default();
        ty_set.insert(ty, Dependency::USED);
        assert_eq!(*ty_s.fv(), ty_set);
        let x = SymbolId::param(ty_s).unwrap();
        let x_s = Symbol::from(x.clone()).into_valid();
        ty_set.insert(x, Dependency::USED);
        assert_eq!(*x_s.fv(), ty_set);
    }
}